
package com.yimixian.app.order;

import com.squareup.picasso.Picasso;
import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.EventBusDomain.CommentMessage;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.adapter.OrderGoodsShowAdapter;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.UMengConstants;
import com.yimixian.app.common.WebViewActivity;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.goods.ShareGoodView;
import com.yimixian.app.model.AppConfig;
import com.yimixian.app.model.Comment;
import com.yimixian.app.model.Order;
import com.yimixian.app.model.User;
import com.yimixian.app.rest.api.CommentPublishAPI;
import com.yimixian.app.rest.api.OrdersDetailAPI;
import com.yimixian.app.ui.ProgressDialogFragment;
import com.yimixian.app.ui.SlideViewPager;
import com.yimixian.app.util.Strings;
import com.yimixian.app.util.UiUtils;

import de.greenrobot.event.EventBus;

import org.json.JSONObject;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import butterknife.ButterKnife;
import butterknife.InjectView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class OrderDetailActivity extends OrderDetailHttpActivity implements
        SlideViewPager.ISlideViewPager {
    public static final String EXTRA_ORDER_ID = "extra_order_id";
    public static final String EXTRA_ORDER_POSITION = "extra_order_position";

    OrderInfoView mOrderInfoView;
    PricesView mPricesView;
    ListView mOrderGoodsListView;
    TextView mPayButton;
    View mPaymentMethodTitle;
    ScrollView mScrollView;
    @InjectView(R.id.slide_view)
    SlideViewPager mSlideView;
    @InjectView(R.id.share_layout)
    ShareGoodView mShareLayout;
    @InjectView(R.id.fl_mask)
    FrameLayout mMasking;

    private String mPaymentMethod;
    private CommentPublishAPI mCommentPublishAPI;
    private OrdersDetailAPI mOrderDetailAPI;
    private String mCommentContent = "";
    private int mTasteCount;
    private int mFreshnessCount;

    private int mGoodId;
    private View mButton;
    private int mOrderId = 0;
    private ProgressDialogFragment mProgressDialogFragment;

    View mOrderStatus;
    View mOrderDetail;
    ImageView mRedBag;
    LinearLayout mContainer;
    Handler mHandler = new Handler();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater layoutInflater = getLayoutInflater().from(this);
        mOrderStatus = layoutInflater.inflate(R.layout.order_status, null);
        mOrderDetail = layoutInflater.inflate(R.layout.order_detail_activity, null);
        mIsPayFinished = true;
        setContentView(R.layout.activity_order_detail);
        hideTopBar();
        ButterKnife.inject(this);
        mSlideView.bind(this);
        mSlideView.showBackButton();
        mSlideView.showBottomBar();
        mSlideView.showDivider();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        mOrderId = getIntent().getIntExtra(EXTRA_ORDER_ID, 0);
        mProgressDialogFragment = UiUtils.showProgressDialog(this, "加载中");
        fetchData(true, OrdersDetailAPI.ORDER_INFO);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    private void setupViews() {
        initView();
        mSlideView.setBottomBarStatus(mOrder.complainUrl, mOrder.commentUrl,
                mOrder.complainBtnName, mOrder.commentBtnName, mOrder);
        LoadRedBagPic(mOrder.shareImgUrl);
        setStatusData();
        mShareLayout.bind(mOrder.shareTitle, mOrder.shareUrl,
                mOrder.shareIcon, mOrder.shareContent);
        mMasking.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mShareLayout != null) {
                    cancelMasking();
                    mShareLayout.closeShareViewWithAnim();
                }
            }
        });
        mOrderDetail.findViewById(R.id.pay_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
//                        UMengConstants.NEW_ORDERDETAIL_PAY);
                Map<String, String> hashMap = new HashMap<>();
                hashMap.put("EVENT", mPaymentMethod.toLowerCase());
                MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                        UMengConstants.NEW_ORDERDETAIL_PAY);
                paymentButtonClicked(mPaymentMethod);
            }
        });
        if (!Strings.isNullOrEmpty(mOrder.statusUrl)) {
            showOrderStatusView();
        }
        mOrderInfoView.bind(mOrder.metadata);

        mPricesView.bind(mOrder.priceComponents, mOrder.priceToPay);
        // mOrderGoodsListView.bind(mOrder.items);
        OrderGoodsShowAdapter mOrderGoodsShowAdapter = new OrderGoodsShowAdapter(this, mOrder.items);
        mOrderGoodsListView.setAdapter(mOrderGoodsShowAdapter);
        mOrderGoodsListView.setEnabled(false);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mOrderGoodsListView
                .getLayoutParams();
        int totalHeight = 0;
        for (int i = 0; i < mOrder.items.size(); i++) {
            View view = mOrderGoodsShowAdapter.getView(i, null, null);
            view.measure(0, 0);
            totalHeight += view.getMeasuredHeight();
        }
        params.height = totalHeight;
        mOrderGoodsListView.setLayoutParams(params);

        if (mScrollView != null) {
            mScrollView.post(new Runnable() {
                @Override
                public void run() {
                    mScrollView.scrollTo(20, 20);
                }
            });
        }

        if (!mOrder.needsPayment || mOrder.paymentDueAt == null) {
            return;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = sdf.parse(mOrder.paymentDueAt);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (date == null)
            return;
        final int countDown = (int) (date.getTime() - System.currentTimeMillis()) / 1000;
        if (countDown <= 0) {
            return;
        }

        mPaymentMethodTitle.setVisibility(View.VISIBLE);
        mPaymentMethodView.setVisibility(View.VISIBLE);
        User user = mDataManager.get(CacheKeys.CURRENT_USER);
        AppConfig appConfig = mDataManager.get(CacheKeys.APP_CONFIG);
        if (mOrder.paymentMethods.contains(ConfirmOrderActivity.PAYMENT_METHOD_WECHAT)) {
            mPaymentMethod = ConfirmOrderActivity.PAYMENT_METHOD_WECHAT;
        } else {
            mPaymentMethod = mOrder.paymentMethods.get(0).getId();
        }

        HashMap<String, String> map = new HashMap<>();
        ArrayList<String> methods = new ArrayList<>();
        for (int i = 0; i < mOrder.paymentMethods.size(); i++) {
            methods.add(mOrder.paymentMethods.get(i).getId());
            map.put(mOrder.paymentMethods.get(i).getId(), mOrder.paymentMethods.get(i).getName());
        }
        if (user != null && appConfig != null) {
            appConfig.mPaymentMethodTitles = map;
            mPaymentMethodView.bind(methods, user.remainingBalance + "",
                    appConfig.mPaymentMethodTitles,
                    mPaymentMethod, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (view instanceof PaymentMethodItemView) {
                                mPaymentMethod = ((PaymentMethodItemView) view).getPayMethodName();
                            }
                        }
                    });
        }

//        ((FrameLayout.LayoutParams) mContentFrame.getLayoutParams()).bottomMargin =
//                getResources().getDimensionPixelSize(R.dimen.bar_height);
//        mBottomBar.setVisibility(View.VISIBLE);
        mBottomBar.setVisibility(View.GONE);

        mPayButton = mSlideView.pay_button;
        mCountDownTextView = mSlideView.count_down_text;

        if (mOrder.paymentMethods != null && mOrder.paymentMethods.size() != 0) {
            mPayButton.setVisibility(View.VISIBLE);
            mPayButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Map<String, String> hashMap = new HashMap<>();
                    hashMap.put("EVENT", mPaymentMethod.toLowerCase());
                    MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                            UMengConstants.NEW_ORDERDETAIL_PAY);
                    paymentButtonClicked(mPaymentMethod);
                }
            });
            countDownTimerStart(countDown);
            mCountDownTextView.setVisibility(View.VISIBLE);
        }
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mSlideView.setCurrentPage(mOrder.indexPage);
            }
        }, 0);

    }

    @Override
    public void onPaymentTimeout() {
        super.onPaymentTimeout();
        mPayButton.setVisibility(View.GONE);
        mCountDownTextView.setVisibility(View.GONE);
    }

    private void showOrderStatusView() {

    }

    private String appendTokenIfNecessary(String url) {
        String token = mDataManager.get(CacheKeys.TOKEN);
        Uri uri = Uri.parse(url);
        if (Strings.isNullOrEmpty(token) || !uri.getHost().endsWith(".1mxian.com")) {
            return url;
        }

        return url + (url.contains("?") ? "&token=" : "?token=") + token;
    }

    @Override
    public void initRequestAPI(String key) {
        if (key != null
                && CommentPublishAPI.COMMENT_PUBLISH.equals(key)) {
            if (mGoodId != 0) {
                mCommentPublishAPI = new CommentPublishAPI(mGoodId,
                        mCommentContent, mTasteCount, mFreshnessCount, this);
            }
        }
        if (key != null
                && OrdersDetailAPI.ORDER_INFO.equals(key)) {
            if (mOrderId != 0) {
                mOrderDetailAPI = new OrdersDetailAPI(mOrderId, mDataManager
                        .<String> get(CacheKeys.TOKEN)
                        , this);

            }
        }
    }

    @Override
    public void onHttpSuccess(String url, JSONObject responseJson) {
        if (url.contains(CommentPublishAPI.COMMENT_PUBLISH) && mCommentPublishAPI != null) {
            Comment comment = mCommentPublishAPI.parseJson(responseJson);
            if (mButton != null) {
                mButton.setVisibility(View.GONE);
            }
            UiUtils.showToast("评论成功");
        }
        if (url.contains(OrdersDetailAPI.ORDER_INFO) && mOrderDetailAPI != null) {
            UiUtils.dismiss(mProgressDialogFragment);
            Order order = mOrderDetailAPI.parseJson(responseJson);
            if (order != null) {
                mOrder = order;
                setupViews();
            }
        }
    }

    @Override
    public void OnHttpFailure(String url, String errorMessage) {
        if (url.contains(OrdersDetailAPI.ORDER_INFO)) {
            UiUtils.showToast(getString(R.string.network_error));
            finish();
        }
    }

    @Override
    public void fetchDataFromNetwork(String key) {
        initRequestAPI(key);
        if (CommentPublishAPI.COMMENT_PUBLISH.equals(key)) {
            if (mCommentPublishAPI != null) {
                mCommentPublishAPI.commentPublish();
            }
        }
        if (OrdersDetailAPI.ORDER_INFO.equals(key)) {
            if (mOrderDetailAPI != null) {
                mOrderDetailAPI.getOrderInfo();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected String getTitleBarText() {
        return "订单详情";
    }

    public void onEventMainThread(CommentMessage message) {
        if (message != null) {
            mCommentContent = message.comment;
            mTasteCount = message.taste;
            mFreshnessCount = message.freshness;
            mGoodId = message.goodId;
            mButton = message.button;
            fetchData(true, CommentPublishAPI.COMMENT_PUBLISH);
        }
    }

    @Override
    public View getLeftView() {
        return mOrderStatus;
    }

    @Override
    public View getRightView() {
        return mOrderDetail;
    }

    @Override
    public void initLeftView() {
        mContainer = (LinearLayout) mOrderStatus.findViewById(R.id.ll_container);
    }

    @Override
    public void initRightView() {
        mPricesView = (PricesView) mOrderDetail.findViewById(R.id.prices);
        mOrderInfoView = (OrderInfoView) mOrderDetail.findViewById(R.id.order_info);
        mOrderGoodsListView = (ListView) mOrderDetail.findViewById(R.id.order_goods_list);
        mPayButton = (TextView) mOrderDetail.findViewById(R.id.pay_button);
        mPaymentMethodTitle = mOrderDetail.findViewById(R.id.pay_method_title);
        mScrollView = (ScrollView) mOrderDetail.findViewById(R.id.content_frame);
        mRedBag = (ImageView) mOrderDetail.findViewById(R.id.iv_red_bag);

    }

    @Override
    public String getLeftTitleName() {
        return "订单状态";
    }

    @Override
    public String getRightTitleName() {
        return "订单详情";
    }

    @Override
    public void onBackButtonClick() {
        onBackPressed();
    }

    public void LoadRedBagPic(String url) {
        if (!TextUtils.isEmpty(url)) {

            mRedBag.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showShareLayout();
                }
            });

            mRedBag.setOnTouchListener(new View.OnTouchListener() {

                float sideSpace = getResources().getDisplayMetrics().density * 20;
                float screenWidth, screenHeight;
                float vWidth, vHeight;
                float downX, downY, startX, startY;
                private boolean isMove = false;

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                    vWidth = v.getWidth();
                    vHeight = v.getHeight();
                    screenWidth = ((View) v.getParent()).getWidth();
                    screenHeight = ((View) v.getParent()).getHeight();
                    FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mRedBag.getLayoutParams();
                    switch (event.getAction()){
                        case MotionEvent.ACTION_DOWN:
                            downX= event.getRawX();
                            downY= event.getRawY();
                            startX = lp.rightMargin;
                            startY = lp.bottomMargin;
                            break;
                        case MotionEvent.ACTION_MOVE:
                            lp.rightMargin = (int) Math.ceil(startX + (downX - event.getRawX()));
                            lp.bottomMargin = (int) Math.ceil(startY + (downY - event.getRawY()));

                            if(lp.rightMargin < sideSpace){
                                lp.rightMargin = (int) sideSpace;
                            }else if(screenWidth - sideSpace < lp.rightMargin + vWidth){
                                lp.rightMargin = (int) (screenWidth - sideSpace - vWidth);
                            }

                            if(lp.bottomMargin < 0){
                                lp.bottomMargin = 0;
                            }else if(lp.bottomMargin + vHeight > screenHeight){
                                lp.bottomMargin = (int) (screenHeight - vHeight);
                            }

                            v.requestLayout();
                            break;
                        case MotionEvent.ACTION_UP:
                            if(lp.rightMargin + vWidth / 2 > screenWidth / 2){
                                lp.rightMargin = (int) (screenWidth - sideSpace - vWidth);
                            }else{
                                lp.rightMargin = (int) sideSpace;
                            }
                            v.requestLayout();
                            if(Math.abs(startX - lp.rightMargin) < 5 && Math.abs(startY - lp.bottomMargin) < 5)
                                v.performClick();
                            break;
                    }
                    return true;
                }
            });

            float sizePromotion = getResources().getDimension(R.dimen.view_footer_bottom2);
            url = DataManager.getInstance().getImageUrl(url,
                    (int) sizePromotion);
            mRedBag.setVisibility(View.VISIBLE);
            Picasso picasso = Picasso.with(this);
            picasso.load(url).into(mRedBag);
        }

    }

    public void showShareLayout() {
        if (mShareLayout.getVisibility() == View.GONE) {
            startMasking();
            mShareLayout.openShareViewWithAnim();
        }
    }

    @Override
    public void onBackPressed() {
        if (mShareLayout != null && mShareLayout.getVisibility() == View.VISIBLE) {
            if (mMasking != null) {
                cancelMasking();
            }
            mShareLayout.closeShareViewWithAnim();
        } else {
            super.onBackPressed();
        }
    }

    public void setStatusData() {
        mContainer.removeAllViews();
        for (int i = 0; i < mOrder.statusItems.size(); i++) {
            final OrderStatusItemView item = new OrderStatusItemView(this);
            if (i == 0) {
                item.hideTopLine();
            }
            if (i > 0 && i == mOrder.statusItems.size() - 1) {
                item.hideBottomLine();
            }
            item.bind(mOrder.statusItems.get(i));
            final Order.orderStatus status = mOrder.statusItems.get(i);
            item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!TextUtils.isEmpty(status.url)) {
                        if (status.url.contains("phone_number")) {
                            String url[] = status.url.split("phone_number=");
                            if (url.length == 2) {
                                Intent intentContact = new Intent(Intent.ACTION_CALL);
                                intentContact.setAction(Intent.ACTION_DIAL);
                                intentContact.setData(Uri.parse("tel:" + url[1]));
                                startActivity(intentContact);
                            }
                        } else {
                            Intent intent = new Intent(OrderDetailActivity.this,
                                    WebViewActivity.class);
                            intent.putExtra(WebViewActivity.EXTRA_URL, status.url);
                            startActivity(intent);
                        }
                    }
                }
            });
            mContainer.addView(item, i);
        }
    }

    private void cancelMasking() {
        AlphaAnimation animation = new AlphaAnimation(1.0f, 0.0f);
        animation.setDuration(200);
        if (mMasking != null) {
            mMasking.startAnimation(animation);
            mMasking.setVisibility(View.GONE);
        }
    }

    public void startMasking() {
        if (mMasking != null) {
            mMasking.setVisibility(View.VISIBLE);
        }
        AlphaAnimation animation = new AlphaAnimation(0.0f, 1.0f);
        animation.setDuration(200);
        if (mMasking != null) {
            mMasking.startAnimation(animation);
        }
    }

    public void onEventMainThread(String message) {
        if (message != null) {
            if (ShareGoodView.SHAREVIEW_CANCEL_MASKING.equals(message)) {
                if (mMasking != null) {
                    cancelMasking();
                }
            }
        }
    }
}
